﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    public class DocumentPropertyController : BaseController
    {
        //
        // GET: /DocumentProperty/

        public DocumentPropertyController()
        {

        }
        [HttpPost]
        [ActionName("add_record_have_property")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult AddRecordHaveProperty(DocumentPropertyModel documentPropertyModel)
        {
            try
            {
                try
                {
                    List<ValidationResult> outError;
                    if (documentPropertyModel.IsValid(out outError))
                    {
                        var dbType = new DocumentProperty
                        {
                            //Id = documentPropertyModel.Id,
                            Name = documentPropertyModel.Name,
                            Type = documentPropertyModel.Type,
                           // CreatorId = documentPropertyModel.CreatorId,
                            IsActive = documentPropertyModel.IsActive,
                            IsDefault = documentPropertyModel.IsDefault,
                            CreatedAt = DateTime.Now,
                            UpdatedAt = DateTime.Now
                        };

                        unitOfWork.DocumentPropertyRepository.Insert(dbType);
                        return Json(SimplyResponse.ResposeWithId(dbType.Id));
                    }
                    else
                    {
                        return Json(new JsonResponse()
                        {
                            Status = false,
                            Result = string.Join("Thêm thế nào đc sai rồi kìa ", outError.Select(o => o.ErrorMessage).ToArray())
                        });
                    }//end ìf
                }
                catch (Exception)
                {
                    return Json(SimplyResponse.Response500());
                    //throw;
                }
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }
        [HttpPut]
        [ActionName("update_record_have_property")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult UpdateRecordHaveProperty(DocumentPropertyModel documentPropertyModel, string modified = "all")
        {
            try
            {
                List<ValidationResult> outError;
                if (documentPropertyModel.IsValid(out outError))
                {
                    var dbDoc = unitOfWork.DocumentPropertyRepository.GetById(documentPropertyModel.Id);
                    if (dbDoc == null)
                    {
                        return Json(new JsonResponse()
                        {
                            Status = false,
                            Result = "không tìm thấy id"
                        });
                    }
                    if (modified.ToUpper().Contains("ISACTIVE"))
                    {
                        dbDoc.IsActive = documentPropertyModel.IsActive;
                    }
                    else//cập nhật lại item
                    {
                        dbDoc.Name = documentPropertyModel.Name;
                        dbDoc.Type = documentPropertyModel.Type;
                        dbDoc.IsActive = documentPropertyModel.IsActive;
                        dbDoc.CreatorId = documentPropertyModel.CreatorId;
                        dbDoc.IsDefault = documentPropertyModel.IsDefault;
                    }
                    dbDoc.UpdatedAt = DateTime.Now;
                    dbDoc.CreatedAt = DateTime.Now;
                    unitOfWork.DocumentPropertyRepository.Update(dbDoc);
                    return Json(SimplyResponse.Response200());
                }
                else
                {
                    return Json(new JsonResponse()
                    {
                        Status = false,
                        Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                    });
                }//end ìf
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }


        /// <summary>
        /// search value ="key";
        /// </summary>
        [HttpGet]
        [ActionName("search_docpro")]
        public JsonResult Search(string key)
        {
            try
            {
                var items = unitOfWork.DocumentPropertyRepository.Search(key);
                return Json(new JsonResponse() { Status = true, Result = items.Select(o => new DocumentPropertyModel(o)) },
                            JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
            }

        }

        [HttpGet]
        [ActionName("get_all_record_have_property")]
        public JsonResult GetAllRecordHaveProperty(int pageSize = 0, int pageIndex = 0)
        {
            if (pageSize <= 0 && pageIndex == 0)
            {
                try
                {
                    var item = unitOfWork.DocumentPropertyRepository.Get();
                    return Json(new JsonResponse()
                                    {
                                        Status = true,
                                        Result = item.Select(o => new DocumentPropertyModel(o)).ToList()
                                    }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                    return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                try
                {
                    var item = unitOfWork.DocumentPropertyRepository.Paging(pageIndex, pageSize);
                    return Json(
                        new JsonResponse()
                            {
                                Status = true,
                                Result = new
                                             {
                                                 pageSize = item.PageSize,
                                                 pageIndex = item.PageIndex,
                                                 PageCount = item.PageCount,
                                                 Item = item.Select(o => new DocumentPropertyModel(o)).ToList()
                                             }
                            }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                    return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
                }
            }
        }

        [HttpPost]
        [ActionName("delete_item")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult Delete(int id)
        {
            try
            {
                unitOfWork.DocumentPropertyRepository.Delete(id);
                return Json(SimplyResponse.Response200());
            }
            catch (Exception ex)
            {
                return Json(SimplyResponse.Response500());
            }
        }

        [HttpGet]
        [ActionName("get_record_have_property")]
        public JsonResult GetRecordHaveProperty(int id)
        {
            try
            {
                var item = unitOfWork.DocumentPropertyRepository.GetById(id);
                return Json(new JsonResponse()
                                {
                                    Status = true,
                                    Result = new DocumentPropertyModel(item)
                                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                return Json(SimplyResponse.Response200());
            }
        }

        [HttpPost]
        [ActionName("save_record_have_property")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult SaveRecordHaveProperty(DocumentPropertyModel model)
        {
            List<ValidationResult> validation;
            if (model != null && model.IsValid(out validation))
            {
                try
                {
                    var documentproperty = new DocumentProperty()
                                               {
                                                   Name = model.Name,

                                               };
                    if (model.Id > 0)
                    {
                        unitOfWork.DocumentPropertyRepository.Update(documentproperty);
                    }
                    else
                    {
                        unitOfWork.DocumentPropertyRepository.Insert(documentproperty);
                    }
                    return Json(SimplyResponse.Response200());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                    return Json(SimplyResponse.Response200());
                }
            }
            else
            {
                return Json(new JsonResponse() { Status = false, Result = "Không thể thêm mới." });
            }
        }



        //public ActionResult Index()
        //{
        //    ViewBag.DropDownList = EnumHelper.SelectListFor<DocumentPropertyType.Property>();
        //    return View();
        //}
    }

}
